#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author : hai.long
import os
import psutil


def find_process_by_port(port):
    """
    获取占用该端口的进程pid
    """
    pid_list = []
    for conn in psutil.net_connections():
        if conn.status == psutil.CONN_LISTEN and conn.laddr.port == port:
            pid_list.append(conn.pid)
    return pid_list


def get_pid_by_port(port):
    """
    获取指定端口的pid
    """
    for conn in psutil.net_connections():
        if conn.status == 'LISTEN' and conn.laddr.port == port:
            return conn.pid
    return None


def close_process(pid):
    """
    根据pid关闭进程
    """
    # 获取对应 PID 的进程信息
    # process = psutil.Process(pid)
    # # 关闭进程
    # process.terminate()
    os.system(f"taskkill /PID {pid} /F")


def quit_print_window():
    from operator import itemgetter
    # 获取所有进程列表 648 11304 11512 14468
    processes = psutil.process_iter()
    p_list = []
    # 遍历进程列表，查找Chrome进程
    for process in processes:
        if process.name() == "chrome.exe":
            p = {"create_time": process.create_time(), "process": process}
            p_list.append(p)
    s_list = sorted(p_list, key=itemgetter("create_time"))
    for p in s_list[-3:]:
        os.system('taskkill /f /im %s' % p["process"].pid)


if __name__ == '__main__':
    # 调用函数获取指定端口的pid
    pid = find_process_by_port(8765)
    print(pid)
    close_process(pid)
